package edu.cmu.vlis.wassup.sender;

import java.io.IOException;
import java.util.Arrays;

import edu.cmu.vlis.wassup.CoordinatorResponder;

public class MPCoordinatorResponder extends CoordinatorResponder{

    private MessageProcessor mp;

    public MPCoordinatorResponder(int port, MessageProcessor msgProcessor) {
        super(port);
        this.mp = msgProcessor;
    }

    @Override
    public void run(){

        String line;
        while(true){
            try {
                Thread.sleep(2000);
                line = this.reader.readLine(); 
                out1.write("MP rcvd from coordinator:"+line + "\n");
                out1.flush();
                if(line.equals("ALIVE?")){
                    this.out.println("YES!");
                }
                if(line.startsWith("Restart:")){
                    String[] parts = line.split(":");
                    this.mp.reset((Arrays.asList(parts)).subList(1, parts.length-1).toArray(new String[0]));
                    this.out.println("YES!");
                    out1.write("Send Yes"+line + "\n");
                    out1.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }catch (NullPointerException npe){
                try {
					out1.write("It seems connection with coordinator is lost..\n");
					 out1.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
               
                this.initialize();
            }
        }

    }
}
